package org.ctstudio.oa.duty.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
@Order(11)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
  private static final String DEF_USERS_BY_USERNAME_QUERY = "select staffId AS username,password,TRUE AS enabled " + "from staff.staffs "
      + "where staffId = ?";
  private static final String DEF_AUTHORITIES_BY_USERNAME_QUERY = "select staffId AS username,rolename AS authority "
      + "from users.userroles " + "where staffId = ?";

  @Autowired
  private DataSource dataSource;

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery(DEF_USERS_BY_USERNAME_QUERY)
        .authoritiesByUsernameQuery(DEF_AUTHORITIES_BY_USERNAME_QUERY).passwordEncoder(new ShaPasswordEncoder(256)).rolePrefix("ROLE_");
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().antMatchers("/staff/**").hasRole("hr").antMatchers("/abnormalsign/approve.do").hasRole("hr")
        .antMatchers("/leave/approve.do").hasRole("supervisor").antMatchers("/manage/**").hasAnyRole("hr", "supervisor").and().formLogin()
        .and().httpBasic();
    http.csrf().ignoringAntMatchers("/manage/h2/**").and().headers().frameOptions().sameOrigin();
  }
}
